package key

import (
	"strings"
)

var TopKey []SingleKey = []SingleKey{{
	SKeyId:  topId,
	Name:    "/",
	FSKeyId: -100,
	Index:   -1,
	Path:    "/",
}}
var KeysMap = make(map[int][]SingleKey)
var idInc int = 1

const errId = -101
const defaultId = -102
const topId = -99

func init() {
	KeysMap[-1] = TopKey
}

type SingleKey struct {
	// id
	SKeyId int
	// 名称
	Name string
	// 父key的id
	FSKeyId int
	// 代表层级
	Index int
	// 到当前key位置的全路径
	Path string
}

type Key struct {
	Id       int
	Label    string
	Path     string
	Children []Key
}

func RegisterSingleKey(key string) {
	split := strings.Split(key, "/")
	keyPutFilter(split[1:])
}

func keyPutFilter(split []string) {
	for i, sKey := range split {
		if i >= 1 {
			if sKey == "" {
				continue
			}
			key := SingleKey{
				Name:  sKey,
				Index: i,
				Path:  getPath(split, i),
			}
			fPath := strings.ReplaceAll(key.Path, "/"+sKey, "")
			_, fId := hasKey(&fPath)
			key.FSKeyId = fId
			b, _ := hasKey(&key.Path)
			if !b {
				key.SKeyId = idInc
				idInc++
				KeysMap[key.Index] = append(KeysMap[key.Index], key)
			}
		} else {
			key := SingleKey{
				Name:    sKey,
				FSKeyId: topId,
				Index:   0,
				Path:    getPath(split, i),
			}
			b, _ := hasKey(&key.Path)
			if !b {
				key.SKeyId = idInc
				idInc++
				KeysMap[key.Index] = append(KeysMap[key.Index], key)
			}
		}
	}

}

func getPath(split []string, i int) string {
	str := split[:i+1]
	join := strings.Join(str, "/")
	return "/" + join
}

// 判断传入键是否在已有的键的切片中
func hasKey(path *string) (bool, int) {
	flag := false
	id := errId
	for _, singleKeys := range KeysMap {
		for _, singleKey := range singleKeys {
			if *path == singleKey.Path {
				flag = true
				id = singleKey.SKeyId
			}
		}
	}
	return flag, id
}
